<?php
/**
 * Created by PhpStorm.
 * User: mac
 * Date: 2019-03-01
 * Time: 23:39
 */

class timer
{
    const HOST = '0.0.0.0';
    const PORT = 8000;
    public $serv = null;

    public function __construct()
    {

        $this->serv = new swoole_server(self::HOST, self::PORT);
        $this->serv->set([
            'worker_num' => 8,
            'max_request' => 2000
        ]);
        $this->serv->on('connect', [$this, 'onConnect']);
        $this->serv->on('receive', [$this, 'onReceive']);
        $this->serv->on('close', [$this, 'onClose']);
        $this->serv->start();
    }

    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client: {$from_id}-{$fd}Connect.\n";
    }

    public function onReceive($serv, $fd, $from_id, $data)
    {
        //每隔3秒发送一条消息
        $timer = swoole_timer_tick(3000, function () use ($serv, $fd) {
            $serv->send($fd, 'every three send');
        });

        //60秒之后执行
        swoole_timer_after(60000, function() use ($serv, $fd, $timer) {
            $serv->send($fd, 'timer clear');
            swoole_timer_clear($timer);
        });
    }

    public function onClose($serv, $fd)
    {
        echo "Client: Close {$fd}.\n";
    }
}

$timer = new timer();